#include <common.h>
#include <device/device.h>
#include <memory/paddr.h>

#define SCREEN_W (MUXDEF(CONFIG_VGA_SIZE_800x600, 800, 400))
#define SCREEN_H (MUXDEF(CONFIG_VGA_SIZE_800x600, 600, 300))

static byte_t* canvas_mem = NULL;

static uint32_t screen_width() {
	return SCREEN_W;
}

static uint32_t screen_height() {
	return SCREEN_H; 
}

uint32_t screen_size() {
  return screen_width() * screen_height() * sizeof(uint32_t);
}

#include <SDL2/SDL.h>

static uint32_t vgactl[2];// VGACTL_ADDR申请了8个字节（两个整字），第一个整字存放宽高，第二个整字存放是否同步

static SDL_Renderer *renderer = NULL;
static SDL_Texture *texture = NULL;

static void init_screen() {
  SDL_Window *window = NULL;
  char title[128];
  sprintf(title, "%s-NPC", str(CONFIG_ISA));
  SDL_Init(SDL_INIT_VIDEO);
  SDL_CreateWindowAndRenderer(
      SCREEN_W * (MUXDEF(CONFIG_VGA_SIZE_400x300, 2, 1)),
      SCREEN_H * (MUXDEF(CONFIG_VGA_SIZE_400x300, 2, 1)),
      0, &window, &renderer);
  SDL_SetWindowTitle(window, title);
  texture = SDL_CreateTexture(renderer, SDL_PIXELFORMAT_ARGB8888,
      SDL_TEXTUREACCESS_STATIC, SCREEN_W, SCREEN_H);
  SDL_RenderPresent(renderer);
}

static inline void update_screen() {
  SDL_UpdateTexture(texture, NULL, canvas_mem, SCREEN_W * sizeof(uint32_t));
  SDL_RenderClear(renderer);
  SDL_RenderCopy(renderer, texture, NULL, NULL);
  SDL_RenderPresent(renderer);
}

void vga_update_screen(){ // get vga_ctl[1]
  // call `update_screen()` when the sync register is non-zero,
  // then zero out the sync register

//   uint32_t is_sync = device_read(VGACTL_ADDR+4,4);
  uint32_t is_sync = vgactl[1];
  if(is_sync) update_screen();
  vgactl[1] = 0;
}

void vga_set_sync(uint32_t data){ // set vga_ctl[1]
  vgactl[1] = data;
}

uint32_t vga_get_hw(){
  return vgactl[0];
}

void vga_init() { // set vga_ctl[0]
//   device_write(VGACTL_ADDR,4,(screen_width() << 16) | screen_height());
  vgactl[0] = (screen_width() << 16) | screen_height();
  canvas_mem = ioaddr_to_ptr(FB_ADDR);
  IFDEF(CONFIG_VGA_MOUNT, init_screen());
  IFDEF(CONFIG_VGA_MOUNT, vga_clear_screen());
}

void vga_clear_screen(){
	memset(canvas_mem, 0, screen_size());
}


